package com.order.model;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.ext.plugin.tablebind.TableBind;
import com.jfinal.ext.render.excel.PoiRender;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.IAtom;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.order.config.ReturnCode;
import com.order.interceptor.sys.LoginInterceptor;
import com.order.shiro.ShiroUtils;
import com.order.utils.DateUtils;
import com.order.utils.Transaction;

/** 
* @ClassName: OrderHead 
* @Description: 订单头
* @author LinBo
* @date 2014年3月22日 下午6:36:49 
*  
*/ 

@TableBind(tableName="order_head", pkName="id")
public class OrderHead extends Model<OrderHead> {
	/** 
	 * @Fields serialVersionUID : 当前类可序列化的版本
	 */  
	private static final long serialVersionUID = 6967931240902587751L;
	public static final OrderHead dao = new OrderHead();
	public static final String ID = "id";
	public static final String ACCOUNT_ID = "account_id";
	public static final String ACCOUNT_NAME = "account_name";
	public static final String PHONE = "phone";
	public static final String ADDRESS = "address";
	public static final String STATUS = "status";
	public static final String CREATE_DATE = "create_date";
	public static final String LAST_UPDATED_BY = "last_updated_by";
	public static final String LAST_UPDATE_DATE = "last_update_date";
	public static final String TOTAL = "total";
	
	/**订单状态*/
	/**已下单，初始化*/
	public static final String STATUS_INIT = "1";
	/**已发货*/
	public static final String STATUS_SHIP = "2";
	/**已签收*/
	public static final String STATUS_RECEIVED = "3";
	/**已评价*/
	public static final String STATUS_FINSH = "4";
	/**无效*/
	public static final String STATUS_INVALID = "0";
	/** 
	* @Title: getOrderJson 
	* @Description: 获取指定订单详情
	* @param page
	* @param pageSize
	* @param orderHeadId
	* @param json
	* @return   
	*/ 
	public Map<String, Object> getOrder(int page, int pageSize, int orderHeadId, 
			JSONObject json, String sortName, String sortOrder) {
		System.out.println(json);
		String select = "select oh.id id, oh.account_id, oh.account_name, "
				+ " oh.phone, oh.address, oh.status, oh.create_date, oh.last_update_date, u.name update_name ";
		String sqlExceptSelect = " from order_head oh left join sys_user u on u.id=oh.last_updated_by "
				+ " where 1=1 ";
		//订单ID
		if(orderHeadId > 0){
			sqlExceptSelect += " and oh.id = " + orderHeadId;
		}
		//状态
		if(!StringKit.isBlank(json.getString("status"))){
			sqlExceptSelect += " and oh.status = " + json.getString("status");
		}
		//下单日期
		if(!StringKit.isBlank(json.getString("create_date_l"))){
			String lDate = json.getString("create_date_l");
			if(lDate.length() > 10){
				lDate = lDate.substring(0, 10);
			}
			sqlExceptSelect += " and oh.create_date >= " + lDate;
		}
		if(!StringKit.isBlank(json.getString("create_date_r"))){
			String rDate = json.getString("create_date_r");
			if(rDate.length() > 10){
				rDate = rDate.substring(0, 10);
			}
			sqlExceptSelect += " and oh.create_date <= " + rDate;
		}
		//收货人
		if(!StringKit.isBlank(json.getString("account_name"))){
			sqlExceptSelect += " and oh.account_name  like '%" + json.getString("account_name") + "%'";
		}
		//排序
		sqlExceptSelect += " order by " + sortName + " " + sortOrder;
		Page<Record> list = Db.paginate(page, pageSize, select, sqlExceptSelect);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list.getList());
		map.put("Total", list.getTotalRow());
		return map;
	}
	/** 
	* @Title: isReadyForShipment 
	* @Description: 订单是否满足发货条件：只为下单状态， 返回不满足id
	* @param ids   
	*/ 
	public List<String> checkForShipment(String[] ids) {
		List<String> notReady = new ArrayList<String>();
		for(int i=0; i<ids.length; i++){
			String status = dao.findById(ids[i]).get(STATUS);
			if(!STATUS_INIT.equals(status)){
				notReady.add(ids[i]);
			}
		}
		return notReady;
	}
	/** 
	* @Title: shipment 
	* @Description: 送餐处理
	* @param ids
	* @return   
	*/ 
	@Before(LoginInterceptor.class)
	public static Map<Integer, String> shipment(String[] ids) {
		Map<Integer, String> map = new HashMap<Integer, String>();
		List<String> notReady = dao.checkForShipment(ids);
		if(!notReady.isEmpty()){
			map.putAll(ReturnCode.getError(ReturnCode.NOT_SHIPMENT_STATUS));
		}
		Transaction tr = new Transaction();
		try {
			//开启事务
			tr.openConnection();
			for(String id : ids){
				//满足条件
				if(!notReady.contains(id)){
					System.out.println("==========================="+DateUtils.getNowTime());
					OrderHead order = dao.findById(id);
					if(order != null){
						order.set(STATUS, STATUS_SHIP)
							.set(LAST_UPDATED_BY, ShiroUtils.getUserId())
							.set(LAST_UPDATE_DATE, DateUtils.getNowTime())
							.update();
					}else{
						map.putAll(ReturnCode.getError(ReturnCode.NOT_EXISTS_ORDER_HEAD));
					}
				}
			}
			tr.commit();
		} catch (SQLException e) {
			e.printStackTrace();
			map.putAll(ReturnCode.getError(ReturnCode.EXCEPTION));
			tr.rollback();
		}finally{
			tr.closeConnection();
		}
		return map;
	}
	/** 
	* @Title: doInvalid 
	* @Description: 设置订单无效
	* @param orderHeadIds
	* @return   
	*/ 
	@Before(LoginInterceptor.class)
	public static Map<Integer, String> doInvalid(String[] orderHeadIds) {
		Map<Integer, String> map = new HashMap<Integer, String>();
		for(String id : orderHeadIds){
			OrderHead order = dao.findById(id);
			if(order != null){
				order.set(STATUS, STATUS_INVALID)
					.set(LAST_UPDATE_DATE, DateUtils.getNowTime())
					.set(LAST_UPDATED_BY, ShiroUtils.getUserId())
					.update();
			}else{
				map.putAll(ReturnCode.getError(ReturnCode.NOT_EXISTS_ORDER_HEAD));
			}
		}
		return map;
	}
	

	/** 
	* @Title: getOrder2 
	* @Description: 报表查询
	* @param page
	* @param pageSize
	* @param orderHeadId
	* @param json
	* @param sortName
	* @param sortOrder
	* @return   
	*/ 
	public Map<String, Object> getOrder2(int page, int pageSize, 
			JSONObject json, String sortName, String sortOrder) {
		System.out.println(json);
		String select = "select oh.id id, oh.account_id, oh.account_name reciver, oh.phone, "
				+ " oh.address, oh.status, oh.create_date, oh.last_update_date, "
				+ " a.name account_name ";
		String sqlExceptSelect = " from order_head oh left join account a on a.id=oh.account_id "
				+ " where 1=1 ";
		//下单日期
		if(!StringKit.isBlank(json.getString("create_date_l"))){
			String lDate = json.getString("create_date_l");
			if(lDate.length() > 10){
				lDate = lDate.substring(0, 10);
			}
			sqlExceptSelect += " and oh.create_date >= '" + lDate + "'";
		}
		if(!StringKit.isBlank(json.getString("create_date_r"))){
			String rDate = json.getString("create_date_r");
			if(rDate.length() > 10){
				rDate = rDate.substring(0, 10);
			}
			sqlExceptSelect += " and oh.create_date <= '" + rDate + "'";
		}
		//收货人
		if(!StringKit.isBlank(json.getString("account_name"))){
			sqlExceptSelect += " and oh.account_name  like '%" + json.getString("account_name") + "%'";
		}
		//排序
		if(StringKit.notBlank(sortName)){
			sqlExceptSelect += " order by " + sortName + " " + sortOrder;
		}
		Page<Record> list = Db.paginate(page, pageSize, select, sqlExceptSelect);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("Rows", list.getList());
		map.put("Total", list.getTotalRow());
		return map;
	}
	/** 
	* @Title: createOrder 
	* @描述: 下单
	* @param jsonId
	* @param jsonNum   
	*/ 
	public void createOrder(final Account account, final List<String> ids, final List<String> nums) {
		Db.tx(new IAtom(){
			@Override
			public boolean run() throws SQLException {
				OrderHead head = new OrderHead();
				head.set(OrderHead.ACCOUNT_ID,account.get(Account.ID))
					.set(OrderHead.ACCOUNT_NAME, account.get(Account.NAME))
					.set(OrderHead.ADDRESS, account.get(Account.ADDRESS))
					.set(OrderHead.PHONE, account.get(Account.PHONE))
					.set(OrderHead.CREATE_DATE, DateUtils.getNowTime())
					.set(OrderHead.STATUS, OrderHead.STATUS_INIT)
					.save();
				int orderHeadId = head.getNumber(OrderHead.ID).intValue();
				double total = 0;
				System.out.println(ids);
				System.out.println(nums);
				for(int i=0; i<ids.size(); i++){
					String sql = "select d.price "
							+ " from dish d, cuisine_dish cd "
							+ " where cd.dish_id = d.id  "
							+ " and cd.id = ? ";
					double price = Db.queryNumber(sql, ids.get(i)).doubleValue();
					double sum = Double.valueOf(nums.get(i)) * price;
					total += sum;
					OrderLine line = new OrderLine();
					line.set(OrderLine.CUISINE_DISH_ID, ids.get(i))
						.set(OrderLine.QUANTITY, nums.get(i))
						.set(OrderLine.ORDER_HEAD_ID, orderHeadId)
						.set(OrderLine.STATUS, OrderHead.STATUS_INIT)
						.set(OrderLine.TOTAL, sum)
						.save();
					System.out.println("======新增订单行："+line);
				}
				head.set(OrderHead.TOTAL, total).update();
				System.out.println("======更新订单头："+head);
				return true;
			}});
		
	}
	/** 
	* @Title: getAllOrder 
	* @描述: 获取客户所有订单
	* @return   
	*/ 
	public List<Record> getAllOrder(String accountId) {
		String sql = " select oh.id, oh.create_date, oh.total "
				+ " from order_head oh "
				+ " where oh.account_id = ? "
				+ " order by oh.create_date desc ";
		List<Record> list = Db.find(sql, accountId);
		for(Record record : list){
			List<Record> line = OrderLine.dao.getAllLine(record.getNumber("id").toString());
			record.set("line", line);
			System.out.println("==========line:"+line);
			System.out.println("==========head:"+list);
		}
		System.out.println(list);
		return list;
	}
	/** 
	* @Title: confirmRecive 
	* @描述: 确认收货
	* @param orderLineId
	* @return   
	*/ 
	public String confirmRecive(String orderLineId) {
//		String msg = "确认成功";
		OrderLine.dao.findById(orderLineId)
			.set(OrderLine.STATUS, OrderHead.STATUS_RECEIVED)
			.update();
		return null;
	}
	/** 
	* @Title: getExcel 
	* @Description: 生成订单Excel
	* @author:	林勃
	* @date:	2014年5月10日 上午11:51:07
	* @param page
	* @param pageSize
	* @param json
	* @return   
	*/ 
	public PoiRender getExcel(int page, int pageSize, JSONObject json) {
		String[] headerStrings = new String[]{
				"客户ID",
				"收货人",
				"地址",
				"电话/手机",
				"下单时间"
		};
		String[] columnStrings = new String[]{
				"ACCOUNT_ID",
				"ACCOUNT_NAME",
				"ADDRESS",
				"PHONE",
				"CREATE_DATE"
		};
		System.out.println((List<?>) dao.getOrder2(page, pageSize, json, "", "").get("Rows"));
		PoiRender poiRender = PoiRender.me((List<?>) dao.getOrder2(page, pageSize, json, "", "").get("Rows"));
		poiRender.fileName("orderReport.xls");
		poiRender.sheetName("订单报表");
		poiRender.cellWidth(5000);
		poiRender.headers(headerStrings);
		poiRender.columns(columnStrings);
		return poiRender;
	}
}
